package com.example.iotest.bio;

import org.junit.Test;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class MyTest1 {

    public static int i = 0;

    public static void main(String[] args) throws IOException, InterruptedException {
        readFile();
//        copyFileByBio();
//        copyFileByNio();
//        copyFileByChars();
    }

    public static void readFile() {
        //获取相对地址文件
        try (FileInputStream fileInputStream = new FileInputStream("src/main/resources/files/11.jpg")) {
            byte[] buffer = new byte[fileInputStream.available()];
            int read = fileInputStream.read(buffer);
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(buffer);
            System.out.println(read + "\n" + encode);

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static void copyFileByBio() {
        try (FileInputStream fileInputStream = new FileInputStream("src/main/resources/files/1.txt");
             FileOutputStream fileOutputStream = new FileOutputStream("src/main/resources/files/2.txt")) {
            byte[] buffer = new byte[1024];
            while (fileInputStream.read(buffer) != -1) {
                fileOutputStream.write(buffer, 0, buffer.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void copyFileByNio() throws IOException {
        FileInputStream fileInputStream = new FileInputStream("src/main/resources/files/1.txt");
        FileChannel channel = fileInputStream.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (channel.read(buffer) != -1) {
            System.out.println();
            buffer.flip();
        }
        FileDescriptor fd = fileInputStream.getFD();
        System.out.println(fd);
    }

    public static void copyFileByChars() throws IOException {

        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("src/main/resources/files/1.txt"), StandardCharsets.UTF_8);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String s = bufferedReader.readLine();
        System.out.println(s);
    }

    @Test
    public  void fileRead() throws IOException {
        FileReader fileReader=new FileReader("src/main/resources/files/1.txt");
        int read = fileReader.read();
        System.out.println((char)read);
        PrintStream printStream=new PrintStream("src/main/resources/files/1.txt");
        printStream.println("1111112asdklajsdkas");
        PrintWriter printWriter=new PrintWriter("src/main/resources/files/1.txt");
        printWriter.println("1222222asdsadffffffff");
        printWriter.flush();
    }

}
